package sc.tool.sqlgen.branchinfo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import sc.prototype.common.ConsoleUtil;

public class DBUtil implements ConsoleUtil {

    public boolean exist(String sql, String columnName) {
        List<Object[]> rows = query(sql, columnName);
        return rows.size() > 0;
    }

    public List<Object[]> query(String sql, String... colNames) {
        ResultSet rs = null;
        Statement stmt = null;
        Connection conn = null;
        List<Object[]> result = new ArrayList<Object[]>();

        try {
            conn = getConn();
            stmt = conn.createStatement();

            rs = stmt.executeQuery(sql);
            int count = 0;
            while (rs.next()) {
                Object[] objValue = new Object[colNames.length];
                for (int i = 0; i < colNames.length; i++) {
                    objValue[i] = rs.getObject(colNames[i]);
                }
                result.add(objValue);
                count++;
                if (count % 10000 == 0) {
                    System.out.println("已经load " + count + "条");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException e) {

                e.printStackTrace();
            }

        }
        return result;
    }

    public static String jdbcUrl = "jdbc:oracle:thin:@db.func.weibopay.com:1521:whpay";
    public static String user = "fosuser";
    public static String password = "fosuser";

    public Connection getConn() throws Exception {
        Class.forName("oracle.jdbc.OracleDriver").newInstance();

        return DriverManager.getConnection(jdbcUrl, user, password);
    }

    public static void main(String[] args) {
        DBUtil u = new DBUtil();
        //        List<Object[]> rows = u.query("select * from tm_branch_info where rownum < 0", "ID", "BRANCH_ID",
        //                "BRANCH_NAME", "UNIFIED_BANK_ID", "BANK_CODE", "PROV_ID", "CITY_ID");
        //        for (Object[] row : rows) {
        //            Console.info("{}, {}", row.length, row);
        //        }
        Console.info("{}", u.exist("select * from tm_branch_info where rownum < 2", "branch_id"));
    }
}
